package com.xianniu.ltc.job;

import cn.devezhao.bizz.security.member.BusinessUnit;
import cn.devezhao.bizz.security.member.Member;
import cn.devezhao.commons.CalendarUtils;
import cn.devezhao.persist4j.engine.ID;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rebuild.core.Application;
import com.rebuild.core.UserContextHolder;
import com.rebuild.core.configuration.general.ClassificationManager;
import com.rebuild.core.privileges.DepartmentService;
import com.rebuild.core.privileges.UserHelper;
import com.rebuild.core.privileges.UserStore;
import com.rebuild.core.privileges.bizz.Department;
import com.rebuild.core.privileges.bizz.User;
import com.rebuild.core.support.ConfigurationItem;
import com.rebuild.core.support.RebuildConfiguration;
import com.rebuild.core.support.integration.QiniuCloud;
import com.rebuild.core.support.mail.IMailService;
import com.rebuild.utils.CommonsUtils;
import com.xianniu.ltc.mapper.TGonghaixiansuoMapper;
import com.xianniu.ltc.mapper.TSihaixiansuoMapper;
import com.xianniu.ltc.model.entity.*;
import com.xianniu.ltc.model.vo.LeadVO;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 商机推送邮件
 * 在商机统计页面上线后弃用-2022.03.04
 * 专门给客服团队推送-2022.03.16
 * @Author: dingyx
 * @Date: 2021/11/3 3:26 下午
 */
@Data
@Slf4j
@Component
@Deprecated
public class NicheScheduleJob extends IJobHandler {
    @Resource
    private TGonghaixiansuoMapper tGonghaixiansuoMapper;
    @Resource
    private TSihaixiansuoMapper tSihaixiansuoMapper;
    @Resource
    private IMailService mailService;

//    @XxlJob("nicheJobHandler")
    @Override
    @Trace
    public void execute() throws Exception{
        // todo 正常情况下，每个公司商机的统计时机都不一样。
        // 都由每个公司的系统账号发起
        // 后续由产品设计该推送
        // 本期就只推送仁科的商机统计资料
        UserContextHolder.setTenant("standard");
        try {
            nicheJobHandler();
        } catch (IOException e) {
            XxlJobHelper.handleFail(e.getCause().getMessage());
            e.printStackTrace();
        }
        XxlJobHelper.handleSuccess();
    }

    public void nicheJobHandler() throws IOException {

        UserStore userStore = Application.getUserStore();
        // 如果用户信息没有初始化完成，首先加载
        if(!userStore.isLoaded()){
            userStore.init(UserContextHolder.getTenant());
        }
        // 根部门
        Department dept = Application.getUserStore().getDepartment(DepartmentService.ROOT_DEPT);
        Set<BusinessUnit> deptSet = dept.getAllChildren();
        // 查询客服俩字的组织部门
        BusinessUnit bs = deptSet.stream().filter(child -> child.getName().contains("客服")).findAny().orElse(null);
        if(Objects.isNull(bs)){
            log.info("{}下没有客服部门", UserContextHolder.getTenant());
            return;
        }
        // 查询客服的部门负责人
        User principal;
        try {
            Department kf = Application.getUserStore().getDepartment(ID.valueOf(bs.getIdentity().toString()));
            principal = Application.getUserStore().getUser(ID.valueOf(kf.getPrincipalId().toString()));
        }catch (Exception e){
            log.info("{}下客服部门没有负责人", UserContextHolder.getTenant());
            e.printStackTrace();
            return;
        }
        // 查询部门成员
        List<String> memberIds = new ArrayList<>();
        Member[] members = UserHelper.getMembers(ID.valueOf(bs.getIdentity().toString()));
        memberIds.add(principal.getId().toString());
        for(Member member : members){
            memberIds.add(member.getIdentity().toString());
        }
        if(Objects.isNull(memberIds) || memberIds.size() <= 0){
            log.info("{}下客服部门没有成员", UserContextHolder.getTenant());
            return;
        }
        // 客服部门负责邮箱
        String email = principal.getEmail();
        // 今天时间
        DateTime today = new DateTime();
        // 一周前时间
        DateTime lastWeek = DateUtil.lastWeek();
        // 查询公海线索
        QueryWrapper<TGonghaixiansuoDTO> gongQuery = new QueryWrapper<>();
        gongQuery.in("CREATED_BY", memberIds);
        gongQuery.between("CREATED_ON",  DateUtil.formatDate(lastWeek), DateUtil.formatDate(today));
        List<TGonghaixiansuoDTO> gongRecords = tGonghaixiansuoMapper.selectList(gongQuery);
        // 查询私海线索
        QueryWrapper<TSihaixiansuoDTO> siQuery = new QueryWrapper<>();
        siQuery.in("CREATED_BY", memberIds);
        siQuery.between("CREATED_ON",  DateUtil.formatDate(lastWeek), DateUtil.formatDate(today));
        List<TSihaixiansuoDTO> siRecords = tSihaixiansuoMapper.selectList(siQuery);
        // 合并线索信息
        JSONArray vos = cleanRecords(gongRecords, siRecords);

        if(CollectionUtil.isEmpty(vos)){
            log.info("时间段：{}-{}内，{}没有创建线索", today, lastWeek, memberIds);
            return;
        }
        sendEmail(email, vos);
    }
    /**
     * 清理商机数据
     * @param gongRecords
     * @param siRecords
     * @return
     */
    private JSONArray cleanRecords(List<TGonghaixiansuoDTO> gongRecords, List<TSihaixiansuoDTO> siRecords) {
        JSONArray vos = new JSONArray();
        if(CollectionUtil.isNotEmpty(gongRecords)){
            for (TGonghaixiansuoDTO gong : gongRecords){
                LeadVO jj = new LeadVO();
                jj.setLeadNo(gong.getXiansuobianhao());
                jj.setLeadName(gong.getLeadName());
                jj.setCreatedOn(gong.getCreatedOn());
                jj.setContactName(gong.getContactName());
                jj.setContactTel(gong.getShoujihaoma());
                jj.setLeadDesc(gong.getRbmiaoshu());
                if(StrUtil.isNotBlank(gong.getXiansuolaiyuan())){
                    jj.setLeadSource(ClassificationManager.instance.getName(ID.valueOf(gong.getXiansuolaiyuan())));
                }
                if(StrUtil.isNotBlank(gong.getGenjinzhuangtai())){
                    jj.setLeadStatus(ClassificationManager.instance.getName(ID.valueOf(gong.getGenjinzhuangtai())));
                }
                jj.setCreator(Application.getUserStore().getUser(ID.valueOf(gong.getCreatedBy())).getFullName());
                vos.add(jj);
            }
        }
        if(CollectionUtil.isNotEmpty(siRecords)){
            for (TSihaixiansuoDTO si : siRecords){
                LeadVO jj = new LeadVO();
                jj.setLeadNo(si.getXiansuobianhao());
                jj.setLeadName(si.getLeadName());
                jj.setCreatedOn(si.getCreatedOn());
                jj.setContactName(si.getContactName());
                jj.setContactTel(si.getShoujihaoma());
                jj.setLeadDesc(si.getRbmiaoshu());
                if(StrUtil.isNotBlank(si.getXiansuolaiyuan())){
                    jj.setLeadSource(ClassificationManager.instance.getName(ID.valueOf(si.getXiansuolaiyuan())));
                }
                if(StrUtil.isNotBlank(si.getGenjinzhuangtai())){
                    jj.setLeadStatus(ClassificationManager.instance.getName(ID.valueOf(si.getGenjinzhuangtai())));
                }
                jj.setCreator(Application.getUserStore().getUser(ID.valueOf(si.getCreatedBy())).getFullName());
                vos.add(jj);
            }
        }
        return vos;
    }
    protected static Element getMailTemplate() {
        String content = CommonsUtils.getStringOfRes("i18n/email.zh_CN.html");
        Assert.notNull(content, "Cannot load template of email");

        Document html = Jsoup.parse(content);
        return html.body();
    }

    private void sendEmail(String emailAddress, JSONArray deptValue) throws IOException {

        String fileName = "商机数据统计" + DatePattern.NORM_DATE_FORMAT.format(new Date()) + ".xlsx";
        File excelFile = new File(fileName);
        ExcelWriter excelWriter = EasyExcel.write(excelFile).build();
        WriteSheet nicheSheet = EasyExcel.
                writerSheet(0, "商机明细").
                head(LeadVO.class).
                build();
        excelWriter.write(deptValue, nicheSheet);
        excelWriter.finish();
        String qiniuLink = QiniuCloud.instance().upload(excelFile);
        String downloadUrl = QiniuCloud.instance().url(qiniuLink, UserContextHolder.getTenant());
        // 标题
        String subject = "客服部门 "+ (DateUtil.month(new Date()) + 1) +"月份第" + DateUtil.weekOfMonth(new Date()) +"周商机统计数据";
        String content = "你好！：<p>&#12288;&#12288;请查收" + subject + "</p>";

        Element mailBody = getMailTemplate();

        mailBody.selectFirst(".rb-title").text(subject);
        mailBody.selectFirst(".rb-content").html(content);
        String htmlContent = mailBody.html();
        // 处理公共变量
        htmlContent = htmlContent.replace("%FROM%", "info@xianniu.cn");
        htmlContent = htmlContent.replace("%TIME%", CalendarUtils.getUTCDateTimeFormat().format(CalendarUtils.now()));
        htmlContent = htmlContent.replace("%APPNAME%", RebuildConfiguration.get(ConfigurationItem.AppName));
        htmlContent = htmlContent.replace("%ASKURL%", downloadUrl);
        content = htmlContent;

        String[] tos = {emailAddress};
        String[] ccs = {emailAddress};
        mailService.sendHtmlMail(tos, ccs, subject, content);
    }
}
